package it.infodea.tapestrydea.pages.demodea;

import it.infodea.tapestrydea.components.livegrid.LGridInsertRow;
import it.infodea.tapestrydea.components.livegrid.LGridRows;
import it.infodea.tapestrydea.entities.demo.Bean;
import it.infodea.tapestrydea.entities.demo.Configuration;
import it.infodea.tapestrydea.entities.demo.Bean.Sesso;
import it.infodea.tapestrydea.support.annotations.PageInfo;
import it.infodea.tapestrydea.support.enumerations.SecurityGroup;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;

@PageInfo(allowedSecurityGroup=SecurityGroup.ANONYMOUS, mode = PageInfo.MODE_NORMAL)
public class LiveGridDemoDea {
	
	private static final List<Bean> beans = new ArrayList<Bean>();
	
	private static final List<Bean> emptyBeans = new ArrayList<Bean>();
	
	@Property
	private Bean bean;
	
	@Persist
	private Configuration configuration;
	
	static{
//		emptyBeans.add(createBean(0));
		for(int i=0; i<4; i++){
			beans.add(createBean(i));
		}
	}
	
	public List<Bean> getBeans(){
		return beans;
	}
	
	public List<Bean> getEmptyBeans(){
		return emptyBeans;
	}
	
	public Configuration getConfiguration() {
		return configuration;
	}
	
	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
	
	public boolean isAsync(){
		return configuration.getAsync().isAsync();
	}
	
	public int getRowsPerPage(){
		return configuration.getRowsPerPage();
	}
	
	@OnEvent(value=LGridRows.ON_DELETE_ROW_EVENT, component="normalGrid")
	void onDelete(int index){
		if(beans.size() > index){
			beans.remove(index);
		}
	}
	
	@OnEvent(LGridInsertRow.ADD_ROW_EVENT)
	void onAdd(Bean bean, Form form){
		System.out.println("normal");
		beans.add(bean);
	}
	
//	@OnEvent(value=LGridRows.ON_DELETE_ROW_EVENT, component="emptyGrid")
//	void onDeleteEmpty(int index){
//		if(emptyBeans.size() > index){
//			emptyBeans.remove(index);
//		}
//	}
//	
//	@OnEvent(value=LGridInsertRow.ADD_ROW_EVENT, component="addRowForm")
//	void onAddEmpty(Bean bean, Form form){
//		System.out.println("empty");
//		emptyBeans.add(bean);
//	}
	
	public Class<?> getBeanClass(){
		return Bean.class;
	}
	
	public String getDate(){
		return Calendar.getInstance().getTime().toString();
	}
	
	public static Bean createBean(int index) {
		Bean b = new Bean();
		b.setTesto("Testo di prova numero " + index);
		b.setTitolo("Titolo " + index);
		b.setSesso( (index%2==0) ? Sesso.FEMMINA : Sesso.MASCHIO);
		b.setCreato(Calendar.getInstance().getTime());
		b.setPagine(Math.abs(new Random().nextInt()%255));
		return b;
	}
	

}

